<?php
	class Fees extends CI_Controller {
	   
       function __construct() {
	       parent::__construct();
           $user = $this->session->userdata('user');
           if (!$user) redirect('main/alogin');
           $this->load->model('fees_db','Fees');
           $this->load->model('school/school_db','School');
           $this->load->model('student/student_db','Student');
           $this->load->model('transport/transport_db','Transport');
           $this->load->model('Dataset_db');
	   }
       
       function newreceipt() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
                echo "You do not have permission to view this page"; exit; 
            }
            $viewtype = "newreceipt";
            $data = array();
            
            $data["fee_item_rows"] = 7;
            $data["receipt_total"] = "0.00";
            
            //print_object($_POST); exit;
            
            
            if($_POST['receipt_regno'] || $_POST["receipt_is_general"]) {
                //print_object($_POST); exit;
                $pdata = array();
                $fields = array(
                		"receipt_regno",
                        "receipt_discount",
                        "ri_feetype",
                        "ri_description",
                        "ri_amount",
                        "receipt_comment"			
                		);
                foreach ($fields as $field) {
                	if(isset($_POST[$field])) $pdata[$field] = $this->input->post($field, true);
                }
                $pdata["receipt_term"] = $this->input->post("receipt_term", true);
                $this->form_validation->set_rules('receipt_term', 'Term', 'trim|required|xss_clean');
                
                if(isset($_POST["receipt_is_general"]) && $_POST["receipt_is_general"] == 1) {
                    $pdata["receipt_is_general"] = 1;
                    $pdata["receipt_student_name"] = $this->input->post("receipt_student_name", true);
                    $this->form_validation->set_rules('receipt_regno', 'Register Number', 'trim|max_length[10]|xss_clean');
                    $this->form_validation->set_rules('receipt_student_name', 'Student Name', 'trim|required|max_length[100]|xss_clean');
                } else {
                    $this->form_validation->set_rules('receipt_regno', 'Register Number', 'trim|required|max_length[10]|xss_clean');
                    $pdata["receipt_is_general"] = 0;
                    $pdata["receipt_student_name"] = "";
                }
                
                
                $this->form_validation->set_rules('receipt_discount', 'Discount', 'trim|xss_clean|numeric');
                $this->form_validation->set_rules('receipt_comment', 'Comment', 'trim|max_length[150]|xss_clean');
                
                $this->form_validation->run();
                
                $data["errors"] = $this->form_validation->error_array();
                if(!is_array($data['errors'])) {
                    $data["errors"] = array();
                }
                
                $ri_length = count($_POST["ri_feetype"]);
                $ri_total = 0;
                $ri_items = array();
                for($ri=0; $ri < $ri_length; $ri++) {
                    $ri_amount = trim($_POST["ri_amount"][$ri]);
                    $ri_itemtype = $_POST["ri_feetype"][$ri];
                    $ri_description = trim($_POST["ri_description"][$ri]);
                    
                    $ri_total = $ri_total + round($ri_amount,2);
                    
                    if($ri_amount!="" && $ri_amount != 0) {
                        if($ri_amount < 0) {
                            array_push($data["errors"],"Item No.".($ri+1)." - Invalid amount.");
                        } else if($ri_amount > 0) {
                            if($ri_itemtype == "") {
                                array_push($data["errors"],"Item No.".($ri+1)." - Item/Category not selected.");
                            } else if($ri_itemtype==6 && $ri_description == "") {
                                array_push($data["errors"],"Item No.".($ri+1)." - Description is mandatory for fee type - Others.");
                            } else {
                                array_push($ri_items,array("ri_feetype"=>$ri_itemtype, "ri_amount"=>$ri_amount, "ri_description"=>$ri_description));
                            }
                        }   
                    }
                }
                $ri_total = $ri_total - round($_POST["receipt_discount"],2);
                $data["receipt_total"] = round($ri_total,2);
                
                $data["postdata"] = $pdata;
                   
                if (count($data["errors"])>0) {
                    //print_object($data["errors"]); exit;
                } else {
                    $data["errors"] = array();
                    $receipt = array();
                    $receipt["receipt_regno"] = $pdata["receipt_regno"];
                    $receipt["receipt_discount"] = $pdata["receipt_discount"];
                    $receipt["receipt_comment"] = $pdata["receipt_comment"];
                    $receipt["receipt_is_general"] = $pdata["receipt_is_general"];
                    $receipt["receipt_student_name"] = $pdata["receipt_student_name"];
                    
                    $term_parts = explode('-',$pdata["receipt_term"]);
                    
                    $receipt["receipt_term_id"] = $term_parts[0];
                    $receipt["receipt_term_year"] = $term_parts[1];
                    
                    $user = $this->session->userdata('user');
                    $receipt["createdby"] = $user['userid'];
                    $receipt["receipt_date"] = unix_to_human(app_time(), true);
                    $receipt["createdon"] = $receipt["receipt_date"];
                    //print_object($pdata); exit;
                    
                    $save_result = $this->Fees->save_receipt($receipt);
                    if($save_result['result'] == 'S') {                        
                        $receipt_no = $save_result["insert_id"];
                        $save_ri_flag = true;   // set to false if any of receipt item save is unsuccessful.
                        foreach($ri_items as $ri_item) {
                            $ri_item["ri_receiptno"] = $receipt_no;
                            $save_ri_result = $this->Fees->save_receipt_item($ri_item);
                            if($save_ri_result['result'] == 'S') {
                            
                            } else {
                                $save_ri_flag = false;
                                array_push($data["errors"],$save_ri_result['error_message']);
                            }
                        }
                        if($save_ri_flag) {
                            $data["successes"] = array('Receipt created successfully.');
                            $viewtype = "viewreceipt";
                            $data["postdata"] = "";
                            $receipt = $this->_get_receipt($receipt_no);
                            if($receipt==null) {
                                $data['errors'] = array("Could not find receipt no $receipt_no");
                            } else {
                                foreach($receipt as $key => $st_item) {
                                    $data[$key] = $st_item;
                                }
                            }
                        }
                        
                    } else {
                        array_push($data["errors"],$save_result['error_message']);   
                    }
                      
                }
            }
            
            $navResult = $this->Dataset_db->buildNav();
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            
            
            $data['feetypelist'] = $this->Fees->get_feetype_list();
            if(isset($pdata["receipt_regno"])) {
                if($receipt["receipt_is_general"]==1) {
                    $data['student_name'] = $receipt['receipt_student_name'];
                } else {
                    $st_result = $this->Student->get_student(array('reg_no'=> $pdata["receipt_regno"]), array('reg_no','student_name','class_label'));
                    if(count($st_result) != 0) {
                        $data['student_name'] = $st_result[0]['student_name'];
                        $data['class_label'] = $st_result[0]['class_label'];
                    }
                }
            }
            
            $data['termlist'] = $this->School->get_receipt_term_list();
            //print_object($data); exit;
            $this->load->view($viewtype,$data); 
       }
       
       private function _get_receipt($receipt_no) {
            $receipt = $this->Fees->get_receipt($receipt_no);            
            //print_object($receipt_result); exit;
            return $receipt;
       }
       
       function viewreceipt($receipt_no, $view="") {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            $data = array();
            if($receipt_no!="") {
                $receipt_no = xss_clean($receipt_no);
                $receipt = $this->_get_receipt($receipt_no);
                if($receipt==null) {
                    $data['errors'] = array("Could not find receipt no $receipt_no");
                } else {
                    foreach($receipt as $key => $st_item) {
                        $data[$key] = $st_item;
                    }
                }
                
                $navResult = $this->Dataset_db->buildNav();
                $data['navs'] = $navResult['links'];
                $data['clabel'] = $navResult['selected']['group'];            
                $data['mlabel'] = $navResult['selected']['item'];
                //print_object($data); exit;
            } else {
                $data['errors'] = array("Invalid request!");
            }
            
            if($view=="print") {
                $data["printview"] = true;
                $data["school"] = $this->School->get_school_info();
                //print_object($data);
                $data['content'] = $this->load->view('viewreceipt',$data,true);
                $this->load->vars($data);
                $this->load->view('print_view');
            } else {
                $this->load->view('viewreceipt',$data); 
            }
               
        }
        
        function feereport() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method) ){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Fee Report";
            $today = date("Y-m-d"); 
            $fromdate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($today)) . " -30 days"));
            $filterdata = array(
                'items' => array(
                    array(
                        'label' => 'Date (From)',
                        'table' => 'rc',
                        'name' => 'receipt_date_from',
                        'col' => 'receipt_date',
                        'check' => '>=',
                        'value' => isset( $_POST["receipt_date_from"] ) ? $_POST["receipt_date_from"] : $fromdate,
                        'type' => 'date',
                        'maxDate' => 0,
                        'data' => ''
                    ),
                    array(
                        'label' => 'Date (To)',
                        'table' => 'rc',
                        'name' => 'receipt_date_to',
                        'col' => 'receipt_date',
                        'check' => '<=',
                        'value' => isset( $_POST["receipt_date_to"] ) ? $_POST["receipt_date_to"] : $today,
                        'type' => 'date',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Term',
                        'table' => 'rc',
                        'name' => 'receipt_term_id',
                        'value' => isset( $_POST["receipt_term_id"] ) ? $_POST["receipt_term_id"] : '',
                        'type' => 'select',
                        'data' => format_list($this->School->get_term_list(),'term_id','term_label')
                    ),
                    array(
                        'label' => 'Academic Year',
                        'table' => 'rc',
                        'name' => 'receipt_term_year',
                        'value' => isset( $_POST["receipt_term_year"] ) ? $_POST["receipt_term_year"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                ),
                'action' => '/fees/feereport',
                'submit' => 'btnSearchReceipt'
            );
            
            $data['show_all'] = true;   
            
            if($_POST) {
                //print_object($filterdata); exit;
            }      
            
            $data['dgdata'] = $this->Fees->build_feereport_dg_data($filterdata);
            
            $data['filterdata'] = $filterdata;
            
            $this->Dataset_db->save_temp_data('feereport',serialize($data['dgdata']));
            $data['sdname'] = 'feereport';
            $data['printurl'] = '/fees/printfeereport';
            $data['exporturl'] = '/fees/exportfeereport';
            
            //print_object($data);exit;
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            //print_object($data); exit;
            $this->load->view('feereport',$data);
        }
        
        function printfeereport($sdname) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            
            if($sdname != "") {
                //$sdata = $this->session->userdata($sdname);
                $sdata = $this->Dataset_db->get_temp_data($sdname);
                if($sdata!='') {
                    $sessdata = unserialize($sdata);
                    //print_object($sessdata);exit;
                    $data['content'] = $this->load->view('elements/print_datagrid',$sessdata, true);
                } else {
                    $data['content'] = "There is nothing to print.";
                }
                
            } else {
                $data['content'] = "There is nothing to print.";
            }
            $data["printview"] = true;
            $data["school"] = $this->School->get_school_info();
            //print_object($data);
            
            $this->load->vars($data);
            $this->load->view('print_view');
        }
        
        function exportfeereport($sdname) {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method)){
            echo "You do not have permission to view this page"; exit; }
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"fee-data.csv\"");
            if($sdname != "") {
                //$sdata = $this->session->userdata($sdname);
                $sdata = $this->Dataset_db->get_temp_data($sdname);
                if($sdata) {
                    $sessdata = unserialize($sdata);
                    //print_object($sessdata);exit;
                    $data = $this->load->view('elements/export_datagrid',$sessdata, true);
                } else {
                    
                }
                
            } else {
                
            }
            
            echo $data;
        }
        
        function searchreceipt($type="") {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method) ){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Search Receipt";
            
            $filterdata = array(
                'items' => array(
                    array(
                        'label' => 'Receipt No.',
                        'table' => 'rc',
                        'name' => 'receipt_no',
                        'value' => isset( $_POST["receipt_no"] ) ? $_POST["receipt_no"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Register No.',
                        'table' => 'rc',
                        'name' => 'receipt_regno',
                        'value' => isset( $_POST["receipt_regno"] ) ? $_POST["receipt_regno"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Date (From)',
                        'table' => 'rc',
                        'name' => 'receipt_date_from',
                        'col' => 'receipt_date',
                        'check' => '>=',
                        'value' => isset( $_POST["receipt_date_from"] ) ? $_POST["receipt_date_from"] : '',
                        'type' => 'date',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Date (To)',
                        'table' => 'rc',
                        'name' => 'receipt_date_to',
                        'col' => 'receipt_date',
                        'check' => '<=',
                        'value' => isset( $_POST["receipt_date_to"] ) ? $_POST["receipt_date_to"] : '',
                        'type' => 'date',
                        'data' => ''
                    ),
                    array(
                        'label' => 'Term',
                        'table' => 'rc',
                        'name' => 'receipt_term_id',
                        'value' => isset( $_POST["receipt_term_id"] ) ? $_POST["receipt_term_id"] : '',
                        'type' => 'select',
                        'data' => format_list($this->School->get_term_list(),'term_id','term_label')
                    ),
                    array(
                        'label' => 'Academic Year',
                        'table' => 'rc',
                        'name' => 'receipt_term_year',
                        'value' => isset( $_POST["receipt_term_year"] ) ? $_POST["receipt_term_year"] : '',
                        'type' => 'text',
                        'data' => ''
                    ),
                ),
                'action' => '/fees/searchreceipt',
                'submit' => 'btnSearchReceipt',
                'meta' => $this->Fees->get_meta(),
                'cols' => isset( $_POST["columns"] ) ? $_POST["columns"] : ''
            );
            
            if($this->input->post('show_all')) {
                $data['show_all'] = true;
            }            
            
            $data['dgdata'] = $this->Fees->build_receipt_dg_data($filterdata);
            
            $data['filterdata'] = $filterdata;
               
            //print_object($data);exit;
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            //print_object($data); exit;
            $this->load->view('searchitem',$data);
        }
        
        function tutionfee() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method) ){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Tution Fee";
            
            //print_object($_POST); exit;
            $data['tutionfee'] = $this->Fees->get_tution_fee();
            
            if($_POST['btnTutionFee']) {
                
                $feedata = array();
                $feelist = array();
                // tutionfee_1_1    Sample fee data name tutionfee_termid_classid
                        
                foreach ($_POST as $key => $post) {
                	$key_parts = explode("_",$key);
                    if(count($key_parts) == 3 && $key_parts[0] == "tutionfee") {
                        $termid = $key_parts[1];
                        $classid = $key_parts[2];
                        $fee = $post;
                        $feelist[$termid."_".$classid] = $post;
                        array_push($feedata,array('termid'=>$termid,'classid'=>$classid,'amount'=>$fee));
                    }
                }
                   
                if (count($data["errors"])>0) {
                    
                } else {
                    $user = $this->session->userdata('user');
                    $createdby = $user['userid'];
                    $createdon = unix_to_human(app_time(), true);
                    
                    $save_result = $this->Fees->save_tutionfee($feedata,$data['tutionfee'],$createdby,$createdon);
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('Tution Fee updated successfully.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']); 
                    }   
                }
                $data['tutionfee'] = $feelist;
            }
            
            $data['classlist'] = $this->School->get_class_list();
            $data['termlist'] = $this->School->get_term_list();
            
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            
            //print_object($data);
            $this->load->view('tutionfee',$data);
        }
        
        function transportfee() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method) ){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Transportation Fee";
            
            
            $data['feelist'] = $this->Transport->get_area_list("area_name ASC");
            
            if($_POST['btnTransportFee']) {
                //print_object($_POST); exit;
                $feedata = array();
                // transportfee_8    Sample fee data name transportfee_areaid
                        
                foreach ($_POST as $key => $post) {
                	$key_parts = explode("_",$key);
                    if(count($key_parts) == 2 && $key_parts[0] == "transportfee") {
                        $areaid = $key_parts[1];
                        $fee = $post;
                        array_push($feedata,array('areaid'=>$areaid,'amount'=>$fee));
                    }
                }
                   
                if (count($data["errors"])>0) {
                    
                } else {                    
                    $save_result = $this->Fees->save_transportfee($feedata,$data['feelist']);
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('Transportation Fee updated successfully.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']); 
                    }   
                }
                $data['tutionfee'] = $feelist;
            }
            
            $data['feelist'] = $this->Transport->get_area_list("area_name ASC");
            
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            
            //print_object($data);
            $this->load->view('transportfee',$data);
        }
        
        function miscfee() {
            if( !$this->Dataset_db->check_access($this->router->class,$this->router->method) ){
            echo "You do not have permission to view this page"; exit; }
            $data['ptitle'] = "Miscellaneous Fee";
            
            
            $data['misclist'] = $this->Fees->get_misc_list();
            
            if($_POST['btnMiscFee']) {
                //print_object($_POST); exit;
                $feedata = array();
                // transportfee_8    Sample fee data name transportfee_areaid
                        
                foreach ($_POST as $key => $post) {
                	$key_parts = explode("_",$key);
                    if(count($key_parts) == 2 && $key_parts[0] == "miscfee") {
                        $feetype_id = $key_parts[1];
                        $fee = $post;
                        array_push($feedata,array('feetype_id'=>$feetype_id,'amount'=>$fee));
                    }
                }
                   
                if (count($data["errors"])>0) {
                    
                } else {                    
                    $save_result = $this->Fees->save_miscfee($feedata,$data['misclist']);
                    if($save_result['result'] == 'S') {
                        $data["successes"] = array('Fees updated successfully.');
                        $data["postdata"] = "";
                    } else {
                        $data["errors"] = array($save_result['error_message']); 
                    }   
                }
            }
            
            $data['misclist'] = $this->Fees->get_misc_list();
            
            $navResult = $this->Dataset_db->buildNav();
            $data['navs'] = $navResult['links'];
            $data['clabel'] = $navResult['selected']['group'];            
            $data['mlabel'] = $navResult['selected']['item'];
            
            //print_object($navResult);
            $this->load->view('miscfee',$data);
        }     
       

}       
/* End of file */